$(function(){
	//滚动条默认最上面
	scrollTo(0,0);
	tabId=$("#tabContent > .tab-pane.active").attr("id");
	//获取当前选中tab页的tabId
	$("#navTabs").find("li").each(function(i){
		$(this).on("click", function () {
			scrollTo(0,0);
			tabId=$("#tabContent > .tab-pane.active").attr("id");
         });
	});
	
	//修改tab标签页href
	$("#"+tabId+" ul > li a").each(function(){
		$(this).attr("href",$(this).attr("href")+tabId);//赋值
	});
	
	//修改tab内容页ID
	$("#"+tabId+" .tab-content div[role='tabpanel']").each(function(){
		$(this).attr("id",$(this).attr("id")+tabId);//赋值
	});
	var deps=null;//获取授权科室
	var roleName=$('#roleName_id').val();//获取角色名称
	if(roleName.indexOf("科室")!=-1){
		deps=$('#deps_id').val();//获取授权科室
		// 修改描述信息 hospInfo
		$("#"+tabId+" #hospInfo").text("科室信息");
	}
	$("#"+tabId+" #search_png").click(function(){
		getYbWeekMonitorData(deps);
	})
	/**
	 * 获取最大出院日期的 日监测数据的出院日期
	 */
	$.post(contextPath + "/DailyRecord/getLastestIssue.dhc", {
		'hospCode' : paramTabPage[tabId].hospCode
	}).done(function(result) {
		if (result.success && result.data && result.data.length > 0) {
			var date = result.data;
			var arr = date.split('-');
			$("#"+tabId+" #endDate").val(date);
			$("#"+tabId+" #startDate").val(arr[0] + "-" + arr[1] + "-01");
			getYbWeekMonitorData(deps);
		} else {
			drgUI.warning('无日监测数据、出院日期为空、院区编码为空！');
		}
	});
});
/**
 * @ Discription:获取查询数据
 * @Autor ：liuhongjun
 * @Date  ：2018年7月19日下午4:08:25
 */
function getYbWeekMonitorData(depCodes){
	//累计监测时间
	var time = $("#"+tabId+" #endDate").val();
	var monitorTime = time.split('-');
	var year = monitorTime[0];
	var month = monitorTime[1];
	$('#'+tabId+' #monitorStartTime').html(year+'年'+'01月');
	$('#'+tabId+' #monitorEndTime').html(year+'年'+month+'月');

	// 角色判断
    var roleName = $("#roles").text();
    if(roleName == "科室") {
    	getIsAbnormal(depCodes);
    } else {
    	getIsAbnormal();
    }
}

/**
 * 跳转异常数据修改页面
 */
function dayMonitor(){
	openTab('/pages/data/dayMonitor.jsp', "日监测数据", "menuMark10413", "menuMark10413" );
}
/**
 * 绘制日监测表格
 */
function drawYbWeekMonitorTables(depCodes){
	var table= null;
	var tdata = null;
	var tb_s='tb'+new Date().getTime();
	var dateFrom = $('input#startDate').val();
	var dateTo = $('input#endDate').val();
	
	$('#'+tabId+' #pageAll').html('');
	$('#'+tabId+' #pageAll').html('<table id="'+tb_s+'" class="display" cellspacing="0" width="100%">'
	+'<thead> <tr><th>&nbsp;</th><th>科室名称</th><th>目标值差距</th><th>累计值差距</th><th>同期增长</th><th>本期值</th><th>目标值</th><th>累计值</th><th>反馈信息</th></tr></thead>'
	+'</table>');
	$.ajax({
		"dataType": 'json', 
        "type": "POST", 
        "url": contextPath+'/DailyRecord/getDepWeekData.dhc', 
        "data": {
        	'fromDate':dateFrom,
    		'toDate':dateTo,
    		'depCodes':depCodes,
    		'hospCode':paramTabPage[tabId].hospCode
        },
        "success": function(result) {
    		if(result!=null){   			
    			var hsp=result.data.shift();
    			if("undefined"==typeof(hsp)){
    				$('#'+tabId+' #hspOutCase').html("-");
	    			$('#'+tabId+' #hspAvgCost').html("-");
	    			$('#'+tabId+' #hspAvgDays').html("-");
	    			$('#'+tabId+' #hspDrugCost').html("-");
    			}else{
    				$('#'+tabId+' #hspOutCase').html(formatNumber(hsp.OUTSUM));
        			$('#'+tabId+' #hspAvgCost').html(formatNumber(hsp.AVGCOST));
        			$('#'+tabId+' #hspAvgDays').html(formatNumber(hsp.AVGBEDDAYS));
        			$('#'+tabId+' #hspDrugCost').html(hsp.DRUGRATIO);
				}
    			tdata=result.data;
    			var columns = [{
									"className" : "details-control",
									"orderable" : false,
									"targets" : [ 0 ]
								},// 复选框
								{
									"data" : "DR_OUT_DEP"
								},{
									"data" : "targetDiff",
									"type" : "number-html",
									"render" : function(obj, type, full) {
										if (full.AVGCOST != null
												&& full.BAVGCOST != null) {
											var diff = (full.AVGCOST - full.BAVGCOST)
													.toFixed(2);
											if (diff > 0)
												return '<span style="color:red;font-weight:bold;">'
														+ formatNumber(diff)
														+ '</span>';
											else
												return '<span>'
														+ formatNumber(diff)
														+ '</span>';
										} else {
											return '<span>-</span>';
										}
									}

								},{
									"data" : "sumDiff",
									"type" : "number-html",
									"render" : function(obj, type, full) {
										if (full.AVGCOST != null
												&& full.SUM_AVGCOST != null) {
											var diff = (full.AVGCOST - full.SUM_AVGCOST)
													.toFixed(2);
											if (diff > 0)
												return '<span style="color:red;font-weight:bold;">'
														+ formatNumber(diff)
														+ '</span>';
											else
												return '<span>'
														+ formatNumber(diff)
														+ '</span>';
										} else {
											return '<span>-</span>';
										}
									}

								},{
									"data" : "spGrow",
									"type" : "number-fate",
									"render" : function(obj, type, full) {
										// 同期增长 = (本期值 - 去年同期累计值) / 去年同期累计值
										if (full.AVGCOST != null&& full.QUOTA_DETAIL_SUM != null&& full.QUOTA_DETAIL_SUM != 0) {
											var diff = ((full.AVGCOST - full.QUOTA_DETAIL_SUM) * 100 / full.QUOTA_DETAIL_SUM)
													.toFixed(2);
											if (diff > 0){
												return '<span style="color:red;font-weight:bold;">'+ diff + '%</span>';
											}else{
												return '<span>' + diff+ '%</span>';
											}
										} else {
											return '<span>-</span>';
										}
									}
								},// 同期增长
								{
									"data" : "avgcost",
									"type" : "numeric-comma",
									"render" : function(obj, type, full) {
										return formatNumber(full.AVGCOST);
									}
								},// 本期值
								{
									"data" : "bavgcost",
									"type" : "numeric-comma",
									"render" : function(obj, type, full) {
										return formatNumber(Math
												.round(full.BAVGCOST * 100) / 100);
									}
								},// 目标值
								{
									"data" : "sumavgcost",
									"type" : "numeric-comma",
									"render" : function(obj, type, full) {
										return formatNumber(full.SUM_AVGCOST);
									}
								},// 累计值
								{
									"data" : "drIsAbnormal",
									"render" : function(obj, type, full) {
										var drIsAbnormal = null;
										drIsAbnormal = '<a href="javascript:ybWeekMonitorResp(\''
												+ full.DR_OUT_DEP
												+ '\',\''
												+ full.BAVGCOST
												+ '\',\''
												+ full.SUM_AVGCOST
												+ '\',\''
												+ full.OUTSUM
												+ '\',\''
												+ full.AVGCOST
												+ '\')"> <i class=\"icon-pencil\"></i></a>';

										return drIsAbnormal;
									}
								} // 反馈信息------待完善
	  		                 ];
    			var paramsDataTables={retrieve:true,paging:false,scrollY:'400px',scrollX:false};
    			var table=$('#'+tabId+' #'+tb_s).dataTableBasic(columns,tdata,paramsDataTables)
    			
                $('#'+tabId+' #'+tb_s).on("click","td.details-control",function () {
                    var nTr = $(this).closest('tr');
                    var row = table.row( nTr );
                    var trInd = row.index();
                    if (row.child.isShown()){ // 判断是否已打开
                        row.child.hide();
                        nTr.removeClass("shown");
                    } else {
                    	$('#'+tabId+' td.details-control').each(function(){
  							var otTr=$(this).closest('tr');
  							var otRow = table.row(otTr);
	  						if (otRow.child.isShown()){ // 判断是否已打开
	  							otRow.child.hide();
	  							// otTr.removeClass("shown");
	  						}
	  						otTr.removeClass("shown");
  						});
  						var rowData=row.data();
                    	nTr.addClass("shown");
                    	row.child("正在加载...").show();
                        fnFormatDetails(table,row,trInd,tdata);
                    }
                })

    		}
        } 
	});
}

function fnFormatDetails(table,row,ind,data){
	var str = "";
	str = str+"<div class = 'row'>";
	str = str+"<div class = 'col-md-12'>";
	str = str+"<div class = 'col-md-3'>&nbsp;</div>";
	str = str+"<div class = 'col-md-3'>&nbsp;</div>";
	str = str+"<div class = 'col-md-2 center'>出院病例数</div>";
	str = str+"<div class = 'col-md-2 center'>平均住院日</div>";
	str = str+"<div class = 'col-md-2 center'>药占比(%)</div>";
	str = str+"</div>";
	str = str+"<div class = 'col-md-12'>";
	str = str+"<div class = 'col-md-3 rightBorder'>";
	str = str+"<div class = 'margin center'>费用超标患者数:<a href=\"javascript:showInOutDetail('"+data[ind].DR_OUT_DEP+"','over')\">"+formatNumber(data[ind].OVERBENCHMARK)+"</a></div>";//未处理
	str = str+"<div class = 'margin center'>&nbsp;</div>";
	str = str+"<div class = 'margin center'>费用未超患者数:<a href=\"javascript:showInOutDetail('"+data[ind].DR_OUT_DEP+"','notover')\">"+formatNumber(data[ind].NOTOVER)+"</a></div>";//未处理
	str = str+"</div>";
	str = str+"<div class = 'col-md-3 rightBorder'>";
	str = str+"<div class = 'margin center'>转入患者数:<a href=\"javascript:showInOutDetail('"+data[ind].DR_OUT_DEP+"','in')\">"+formatNumber(data[ind].DEPIN)+"</a></div>";
	str = str+"<div class = 'margin center'>&nbsp;</div>";
	str = str+"<div class = 'margin center'>转出患者数:<a href=\"javascript:showInOutDetail('"+data[ind].DR_OUT_DEP+"','out')\">"+formatNumber(data[ind].DEPOUT)+"</a></div>";
	str = str+"</div>";
	str = str+"<div class = 'col-md-2 rightBorder'>";
	str = str+"<div class = 'margin center'>本期值:"+(data[ind].OUTSUM==null?"-":formatNumber(data[ind].OUTSUM))+"</div>";
	str = str+"<div class = 'margin center'>累计值:"+(data[ind].SUM_OUTSUM==null?"-":formatNumber(data[ind].SUM_OUTSUM))+"</div>";
	str = str+"<div class = 'margin center'>&nbsp;</div>";
	str = str+"</div>";
	str = str+"<div class = 'col-md-2 rightBorder'>";
	str = str+"<div class = 'margin center'>本期值:"+(data[ind].AVGBEDDAYS==null?"-":formatNumber(data[ind].AVGBEDDAYS))+"</div>";
	str = str+"<div class = 'margin center'>目标值:"+(data[ind].BAVGDAYS ==null?"-":formatNumber(data[ind].BAVGDAYS))+"</div>";
	str = str+"<div class = 'margin center'>累计值:"+(data[ind].SUM_AVGBEDDAYS==null?"-":formatNumber(data[ind].SUM_AVGBEDDAYS))+"</div>";
	str = str+"</div>";
	str = str+"<div class = 'col-md-2'>";
	str = str+"<div class = 'margin center'>本期值:"+(data[ind].DRUGRATIO==null?"-":data[ind].DRUGRATIO)+"</div>";
	str = str+"<div class = 'margin center'>目标值:"+(data[ind].BDRUGCOSTRATIO==null?"-":data[ind].BDRUGCOSTRATIO)+"</div>";
	str = str+"<div class = 'margin center'>累计值:"+(data[ind].SUM_DRUGRATION==null?"-":data[ind].SUM_DRUGRATION)+"</div>";
	str = str+"</div>";
	str = str+"</div>";
	str = str+"</div>";
	row.child(str).show();
    }

//跳转病例明细
function showInOutDetail(depName,type) {
	var dateFrom = $('input#startDate').val();
	var dateTo = $('input#endDate').val();
	openTab('/pages/ybHome/changeDep.jsp', '病例明细', '病例明细'+depName+'Case'+type, '病例明细'+depName+'Case'+type, {fromDate:dateFrom,toDate:dateTo,depName:depName, type: type});

}

//标杆悬停
// $(window).scroll(onScroll);
function onScroll() {
	var scrollY = $(window).scrollTop();
	var top=null;
	try{
		if($('#'+tabId+' #detail-popover').offset()!=undefined){
			top=$('#'+tabId+' #detail-popover').offset().top;
		}
	}catch (e){
		console.log(e);
	}
	if((top-scrollY<=10)){
		$('#'+tabId+' #detail-popover thead').removeClass("topgreat").removeClass("hoverOut").addClass("topless");
	}else if((top-scrollY>=10)){
		$('#'+tabId+' #detail-popover thead').removeClass("topless").removeClass("hoverOut").addClass("topgreat");
	}
    var sY = $(window).scrollTop();
    if((sY>60)){
    	$('#'+tabId+' #date_div').removeClass("outShow").removeClass("hoverOut").addClass("topShow");
    }else if((sY<=60)){
    	$('#'+tabId+' #date_div').removeClass("topShow").removeClass("hoverOut").addClass("outShow");
	}
    
}
//展开日期标杆
function opc1(){
	if ($('#'+tabId+' #date_div').css('position')=='fixed') {
		$('#'+tabId+' #date_div').removeClass("hoverOut").addClass("hoverIn");
	}
}
//收起日期标杆
function opc0(){
	if ($('#'+tabId+' #date_div').css('position')=='fixed') {
		$('#'+tabId+' #date_div').removeClass("hoverIn").addClass("hoverOut");
	}
}


//医保周监测反馈信息
/**
 * depName 科室名称
 * bavgcost 目标值
 * sumavgcost 累计次均费用
 * outsum 出院人数
 * avgcost 次均费用
 */
function ybWeekMonitorResp(depName,bavgcost,sumavgcost,outsum,avgcost) {
	var dateFrom = $('input#startDate').val();
	var dateTo = $('input#endDate').val();
	var info=null;
	if(avgcost!=null&&bavgcost!=null){
		if(avgcost>bavgcost){//修改判断条件
			info = '未达标';
		}else{
			info = '已达标';
		}
	}else{
		info='';
	}
	var reInfo1="尊敬的"+depName+"科领导:<br>"+"贵科室次均费用目标值为"+formatNumber(bavgcost)+"元,科室"+$('#'+tabId+' #monitorStartTime').html()+"~"+$('#'+tabId+' #monitorEndTime').html()+"累计次均费用为"+formatNumber(sumavgcost)+"元<br>"+dateFrom+"至"+dateTo+
	"<br>出院人数为："+formatNumber(outsum)+"<br>次均费用为："+formatNumber(avgcost)+"元  "+info+"<br>感谢贵科室对医保办工作的支持！如有疑问，请随时联系我们！";
	$('#editDialog .modal-content').css({'width':'400px'});
	$('#editDialog .modal-body').html(reInfo1);
	$('#editDialog').modal('show');
}
/**
 * @ Discription:检测异常数据
 * @Autor ：liuhongjun
 * @Date  ：2018年11月6日下午7:07:28
 */
function getIsAbnormal(depCodes){
    var dateFrom = $("#"+tabId+" #startDate").val();
    var dateTo = $("#"+tabId+" #endDate").val();
    //判断数据是否全部是正常数据，如有异常数据存在，进行提示。
    $.post( contextPath +"/DailyRecord/getIsAbnormal.dhc",{
        'fromDate':dateFrom,
        'toDate':dateTo,
        'depCodes':depCodes,
        'hospCode':paramTabPage[tabId].hospCode
    }).done(function(result){
    	if(result){
            var sum=result.data;
            if(sum==0){//没有异常数据 展示数据
                drawYbWeekMonitorTables(depCodes);
            }else{
                drgUI.confirm({
                    content : '您查询的'+dateFrom+'至'+dateTo+'时间段内'+'，有'+sum+'条数据需要进行科室修改，点击“确定”进入科室修改页面，点击“继续”继续查看监测结果',
                    btnl:'确定',
                    btnr:'继续',
                    callSure : function() {
                        dayMonitor(depCodes);
                    },
                    callCancel : function(){
                        drawYbWeekMonitorTables(depCodes);
                    }
                });
            }
    	}
    });
}
